# -*- coding: utf-8 -*-


# cmap2owl -- Helper application to convert from concept maps to OWL ontologies
# Copyright (c) 2008-2013  Rodrigo Rizzi Starr
#  
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


'''
Each linguistic rule detects some features of a phrase, if it is tagged
correctly. Some rules aply only to the concepts, other only to the linking
phrase, others to the complete phrase.

@author: Rodrigo Rizzi Starr
@copyright: Copyright © 2008-2013 Rodrigo Rizzi Starr
@license: MIT License
@contact: rodrigo.starr@gmail.com
'''


import re
from collections import namedtuple


class LinguisticRule(object):
    '''This abstract class defines the interface for a rule that takes into
       account the tags in a Phrase (a Concept + LinkingPhrase + Concept). A
       rule may apply to the first concept, the linkingPhrase, the second
       concept or the whole phrase.

       Each Phrase or part of phrase may activate several instances of the same
       rule.
    '''

    def __init__(self):
        pass

    def apply(self, phrase):
        pass


class ParticipleRelation(LinguisticRule):
    '''Every linkingPhrase of the type:
          é/V ?x/PCP ?y/PREP* (?y/PREP)?
       becomes a relation of type:
          ?x?y.capitalize()
       that is global but restricted to the classes on left and right.
    '''

    def __init__(self):
        self.recognizer = re.compile(ur'é/V\s([^/]+)/PCP\s([^/]+)/PREP\S*(\s[^/]+/PREP)*',
                                     re.IGNORECASE)

    def apply(self, phrase):
        matches = self.recognizer.match(phrase.lpTaggedAsText)
        if matches != None:
            groups = matches.groups()
            propertyName = groups[0].lower() + ''.join(w.capitalize() for w in groups[1:] if w != None)
            return [(self.__class__.__name__, propertyName)]
        else:
            return []

    
# Holds the result of a succesfull application of LogicalConnective rule
LogicalConnectiveResult = namedtuple('LogicalConnectiveResult',
                                   ['rule', 'nodeId', 
                                    'listOfClasses', 'listOfClassLabels'])


class LogicalConnectivePhrase(LinguisticRule):
    '''Every concept (first or second) of the type:
          [?x/N,/,] ?/KC ?y/N
       becomes a conjunction or disjunction of possible classes:
          ?x.capitalize() and/or ?y.capitalize().

       This class must be subclassed to define the connectives used ('and' or
       'or')
    '''

    def __init__(self, conectives):
        self.recognizer = re.compile(ur'(?P<firstNoun>[^/]+)/N\s+'
                                       '(,/,\s*[^/]+/N\s*)*'
                                       '\s*(%s)/KC\s+'
                                       '(?P<lastNoun>[^/]+)/N' % conectives,
                                     re.IGNORECASE)
        self.extraRecognizer = re.compile(ur',/,\s*([^/]+)/N\s*',
                                           re.IGNORECASE)

    def applyTo(self, taggedString, string, nodeId):
        matches = self.recognizer.match(taggedString)
        if matches != None:
            
            groups = matches.groupdict()
            classes = [groups['firstNoun'].capitalize(),]

            matches = self.extraRecognizer.findall(taggedString)
            if len(matches) > 0:
                classes.extend([c.capitalize() for c in matches])
            classes.append(groups['lastNoun'].capitalize())

            result = LogicalConnectiveResult(rule = self.__class__.__name__,
                                           nodeId = nodeId, 
                                           listOfClasses = classes,
                                           listOfClassLabels = classes,)
            return [result]
        else:
            return []
    
    def apply(self, phrase):
        instances = self.applyTo(phrase.firstTaggedAsText, 
                                 phrase.lhConcept, 
                                 phrase.lhConceptId)
        instances.extend(self.applyTo(phrase.secondTaggedAsText,
                                      phrase.rhConcept,
                                      phrase.rhConceptId))
        return instances
        
    
class ConjunctionClasses(LogicalConnectivePhrase):
    '''Every concept (first or second) of the type:
          [?x/N,/,] e/KC ?y/N
       becomes a conjunction of possible classes:
          ?x.capitalize() and ?y.capitalize().
    '''

    def __init__(self):
        LogicalConnectivePhrase.__init__(self, u'e|&')

    
class DisjunctionClasses(LogicalConnectivePhrase):
    '''Every concept (first or second) of the type:
          [?x/N,/,] ou/KC ?y/N
       becomes a conjunction of possible classes:
          ?x.capitalize() or ?y.capitalize().
    '''

    def __init__(self):
        LogicalConnectivePhrase.__init__(self, u'ou')

        
# Holds the result of a succesfull application of a semantic phrase
AdjectivePhraseResult = namedtuple('AdjectivePhraseResult',
                                   ['rule', 'nodeId', 
                                    'baseClass', 'derivedClass',
                                    'baseClassText', 
                                    'derivedClassText'])


class AdjectivePhrase(LinguisticRule):
    '''Every concept (first or second) of the type:
          ?x/N d?/PREP|? ?y/N [?z/ADJ]
       becomes two possible classes related by a superclass-subclass relation:
          ?x.capitalize() and ?x.capitalize()?y.capitalize().

       It tries to group all 'adjective phrases' together separated from the
       first noun, to generate less options (and an easier implementation)
    '''

    def __init__(self):
        self.recognizer = re.compile(ur'^(?P<noun>[^/]+)/N\s'
                                       '(?P<preposition>[^/]+)/PREP(\S*)\s'
                                       '(?P<qualityNoun>[^/]+)/N'
                                       '(\s(?P<adjective>[^/]+)/ADJ)?', 
                                     re.IGNORECASE)

    def applyTo(self, taggedString, string, nodeId):
        matches = self.recognizer.match(taggedString)
        if matches != None:
            groups = matches.groupdict()
            baseClass = groups['noun'].capitalize()

            words = taggedString.split(' ')
            derivedClass = ''
            pair = re.compile(r'([^/]+)/([^/]+)')
            for word in words:
                word = pair.sub(r'\1', word)
                derivedClass += word.capitalize()
            result = AdjectivePhraseResult(rule = self.__class__.__name__,
                                           nodeId = nodeId, 
                                           baseClass = baseClass,
                                           derivedClass = derivedClass,
                                           baseClassText = baseClass,
                                           derivedClassText = string)
            return [result]
        else:
            return []
    
    def apply(self, phrase):
        instances = self.applyTo(phrase.firstTaggedAsText, 
                                 phrase.lhConcept, 
                                 phrase.lhConceptId)
        instances.extend(self.applyTo(phrase.secondTaggedAsText,
                                      phrase.rhConcept,
                                      phrase.rhConceptId))
        return instances

    
class DerivedClass(LinguisticRule):
    '''Every concept (first or second) of the type:
          ?x/N ?y/ADJ
       becomes two possible classes:
          ?x.capitalize() and ?x.capitalize()?y.capitalize().
    '''

    def __init__(self):
        self.recognizer = re.compile(ur'(?P<noun>[^/]+)/N\s'
                                       '(?P<adjective>[^/]+)/ADJ', 
                                     re.IGNORECASE)

    def applyTo(self, taggedString, string, nodeId):
        matches = self.recognizer.match(taggedString)
        if matches != None:
            groups = matches.groupdict()
            
            baseClass = groups['noun'].capitalize()
            derivedClass = baseClass + groups['adjective'].capitalize()

            result = AdjectivePhraseResult(rule = self.__class__.__name__,
                                           nodeId = nodeId, 
                                           baseClass = baseClass,
                                           derivedClass = derivedClass,
                                           baseClassText = baseClass,
                                           derivedClassText = string)
            return [result]
        else:
            return []
    
    def apply(self, phrase):
        instances = self.applyTo(phrase.firstTaggedAsText, 
                                 phrase.lhConcept, 
                                 phrase.lhConceptId)
        instances.extend(self.applyTo(phrase.secondTaggedAsText,
                                      phrase.rhConcept,
                                      phrase.rhConceptId))
        return instances

